﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.PregnancyTest.API.Application.Command;
using S.PregnancyTest.API.Dto;
using S.PregnancyTest.Domain;
using S.PregnancyTest.Domain.Model;
using S.PregnancyTest.Infrastructure.Interface;

namespace S.PregnancyTest.API.Application.CommandHandlers
{
    /// <summary>
    /// 删除种母妊检具体实现
    /// </summary>
    public class PregnancyTestDeleteHandler : IRequestHandler<PregnancyTestDeleteCommand, bool>
    {

        private readonly IPregnancyTestRepository repository;

        private readonly MyDbContext dbContext;

        private readonly IMapper mapper;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public PregnancyTestDeleteHandler(IPregnancyTestRepository repository, MyDbContext dbContext, IMapper mapper, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.dbContext = dbContext;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        public async Task<bool> Handle(PregnancyTestDeleteCommand request, CancellationToken cancellationToken)
        {
            string Gateway = configuration.GetValue<string>("Gateway");
            //获取到所有要删除的妊检信息
            List<PregnancyTestModel> PregnancyItem = repository.GetAllAsync().Result.Where(x => request.PregnancytestIds.Contains(x.PregnancytestId.ToString())).ToList();

            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    //循环批量删除的数据
                    foreach (var item in PregnancyItem)
                    {
                        repository.DeleteAsync(item.PregnancytestId);  //删除妊检信息

                        #region 修改种母历史记录

                        EditBreed editBreed = new EditBreed();

                        editBreed.EarTag = item.EarTag;

                        //反填种母历史记录
                        var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                        //将获取到的种母历史记录序列化
                        var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                        if (response.DeliveryDate != null)
                        {
                            tran.Rollback();
                            return false;
                        }

                        //修改种母历史记录
                        response.PregnancyDate = null; //修改妊检日期
                        response.PregnancytestResult = 0; //修改妊检结果
                        response.IsEditor = true;   //修改可编辑的状态
                        //修改种母历史记录
                        HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                        #endregion

                        #region 修改档案信息

                        ArchivesDto archivesDto = new ArchivesDto();

                        //修改档案信息
                        EditReproductivePresenceState.UpdateReproductivePresenceState(item.EarTag, 1, 0, DateTime.Now, Gateway);
                        //修改流转状态
                        EditWanderState.EditWander(item.EarTag, 2, Gateway);

                        #endregion

                        #region 删除转舍信息

                        HttpClientHelper.DeleteResponse($"{Gateway}/transset/api/TransFer/DeleteSheepTransFer?EarTag=" + item.EarTag + "&SurrenderDate=" + item.PregnancyDate);

                        #endregion

                        #region 修改配种表状态

                        HttpClientHelper.PostResponse($"{Gateway}/BreedSet/api/MaternalMating/UpdateHuiState?ear=" + item.EarTag + "", "");

                        #endregion

                    }

                    //事物提交
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    return false;
                }
            }

        }



        public class EditBreed
        {
            /// <summary>
            /// 可视耳号
            /// </summary>
            public string? EarTag { get; set; }
        }

        public class ArchivesDto
        {
            /// <summary>
            /// 可视耳号
            /// </summary>
            public string? EarTag { get; set; }

            /// <summary>
            /// 修改标识
            /// </summary>
            public int Uflag { get; set; }

            /// <summary>
            /// 状态
            /// </summary>
            public int UState { get; set; }
        }

    }
}
